<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false" content="添加题目">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form class="ant-advanced-search-form" labelAlign="right">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="题目类型">
              <a-select v-model="queryParam.cate" placeholder="请选择类型" style="width: 200px">
                <a-select-option value="单选"> 单选 </a-select-option>
                <a-select-option value="多选"> 多选 </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="题目类别">
              <a-select
                show-search
                v-model="queryParam.type"
                placeholder="请搜索题目分类"
                style="width: 200px"
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="typeFetching ? undefined : null"
                @search="handleSearchType"
                @change="handleTypeChange"
                allowClear
              >
                <a-spin v-if="typeFetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="item in typeList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="题目名称">
              <a-input v-model="queryParam.name" style="width: 200px" placeholder="请输入题目名称" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="6" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="handleSearch"> 查询 </a-button>
            <a-button :style="{ marginLeft: '8px' }" @click="reset"> 重置 </a-button>
          </a-col>
        </a-row>
      </a-form>
      <div class="content">
        <div class="table-header">
          <a-button type="primary" @click="edit({}, 0)">新增</a-button>
          <a-button type="primary" style="margin-left: 12px" @click="$refs.BatchAdd.showDrawer()">批量添加</a-button>
          <!-- <a-button type="primary" style="margin-left: 12px" @click="showDistributeModal">
            分配题目
          </a-button> -->
        </div>
        <div>
          <!-- :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }" -->
          <a-table
            :columns="columns"
            :data-source="listData"
            rowKey="id"
            bordered
            :pagination="pagination"
            @change="handleTableChange"
            :loading="loading"
          >
            <template slot="type" slot-scope="text, record">
              {{ text.name }}
            </template>
            <template slot="operation" slot-scope="text, record">
              <a ref="javascript:;" @click.stop="$refs.detail.showDrawer(record)" style="color: #409eff">查看</a>
              <a-divider type="vertical" />
              <a ref="javascript:;" @click.stop="edit(record, 1)" style="color: #409eff">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除操作?" ok-text="确定" cancel-text="取消" @confirm="deleteItem(record)">
                <a ref="javascript:;" @click.stop="() => {}" style="color: #67c23a">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </div>
    </a-card>
    <BatchAdd ref="BatchAdd" />
    <detail ref="detail" />
    <edit @refresh="refresh" ref="edit" />
    <a-modal
      title="分配题目"
      :visible="showModal"
      :confirm-loading="modalLoading"
      @ok="handleDistribute"
      @cancel="showModal = false"
    >
      <a-alert
        show-icon
        :message="`您已选中${queryParam.type ? pagination.total : selectedRowKeys.length}条题目`"
        type="warning"
        closable
      />
      <a-form style="margin-top: 12px" :form="modalForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="被分配人" required>
          <a-select
            v-decorator="['user_ids', { rules: [{ required: true, message: '请选择被分配人' }] }]"
            mode="multiple"
            show-search
            placeholder="请选择被分配人"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="userFetching ? undefined : null"
            @search="handleSearchUser"
            @change="handleUserChange"
          >
            <a-spin v-if="userFetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in userList" :key="item.id">
              {{ item.nickname }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import Detail from './detail.vue'
import BatchAdd from './batchAdd.vue'
import Edit from './edit.vue'
import { getQuestionList, deleteQuestion, distributeQuestion } from '@/api/question'
import { getTypeList } from '@/api/questionType'
import { getUserList } from '@/api/user'
const columns = [
  {
    title: '类型',
    dataIndex: 'cate',
    width: 100,
    key: 'cate',
  },
  {
    title: '题目',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
  },
  {
    title: '类别',
    dataIndex: 'type',
    key: 'type',
    ellipsis: true,
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 200,
    scopedSlots: { customRender: 'operation' },
  },
]

export default {
  components: {
    Detail,
    Edit,
    BatchAdd,
  },
  data() {
    return {
      modalForm: this.$form.createForm(this),
      listData: [],
      columns,
      pagination: {},
      queryParam: {},
      loading: false,
      typeList: [],
      selectedRowKeys: [],
      showModal: false,
      modalLoading: false,
      userList: [],
      typeFetching: false,
      userFetching: false,
    }
  },
  created() {
    this.getListData({ page: 1, page_size: 10 })
  },
  methods: {
    edit(record = {}, mode) {
      this.$refs.edit.showDrawer(record, mode)
    },
    //搜索
    handleSearch(e) {
      e.preventDefault()
      this.getListData({ page: 1, page_size: 10 })
    },
    // 分页
    handleTableChange(pagination) {
      this.pagination = {
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
      }
      this.getListData({
        page: pagination.current,
        page_size: pagination.pageSize,
      })
    },
    getListData(params = {}) {
      this.loading = true
      getQuestionList({
        ...params,
        ...this.queryParam,
      })
        .then((res) => {
          this.listData = res.data
          this.pagination = {
            total: res.total,
            pageNum: res.page,
            pageSize: res.page_size,
            showTotal: () => {
              return `共计${res.total}条`
            },
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    reset() {
      this.queryParam = {}
    },
    refresh() {
      this.getListData({
        page: this.pagination.pageNum,
        page_size: this.pagination.pageSize,
      })
    },
    deleteItem(record) {
      deleteQuestion(record.id).then((res) => {
        this.$message.success('删除成功')
        if (this.listData.length === 1 && this.pagination.pageNum > 1) {
          this.pagination.pageNum -= 1
        }
        this.refresh()
      })
    },
    //获取类型请求
    searchTypeRequest(name) {
      this.typeFetching = true
      getTypeList({ page: 1, page_size: 10, name: name })
        .then((res) => {
          this.typeList = res.data
        })
        .finally(() => {
          this.fetching = false
        })
    },
    //搜索题目类别
    handleSearchType(value) {
      this.searchTypeRequest(value)
    },
    //搜索题目类别
    handleTypeChange(value) {
      this.searchTypeRequest(value)
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    //展示分配题目Modal
    showDistributeModal() {
      if (this.queryParam.type) {
        this.showModal = true
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请勾选您要分配的题目')
        return
      }
      this.showModal = true
    },
    //分配题目
    handleDistribute(e) {
      e.preventDefault()
      this.modalForm.validateFields((err, values) => {
        if (!err) {
          const data = {
            user_ids: values.user_ids.toString(),
            question_ids: this.selectedRowKeys.toString(),
          }
          if (this.queryParam.type) {
            data.type = this.queryParam.type
          }
          this.modalLoading = true
          distributeQuestion(data)
            .then((res) => {
              this.showModal = false
              this.$message.success(res.detail)
            })
            .finally(() => {
              this.modalLoading = false
            })
        }
      })
    },
    //获取用户请求
    searchUserRequest(name) {
      this.userFetching = true
      getUserList({ page: 1, page_size: 10, nickname: name })
        .then((res) => {
          this.userList = res.data
        })
        .finally(() => {
          this.userFetching = false
        })
    },
    //搜索用户
    handleSearchUser(value) {
      this.searchUserRequest(value)
    },
    //搜索用户
    handleUserChange(value) {
      this.searchUserRequest(value)
    },
  },
}
</script>
<style lang="less" scoped>
.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}

.content {
  margin: 12px;

  .table-header {
    margin-bottom: 12px;
  }
}
</style>
